package com.pronhub.cloud.shop.web.controller;

import com.pronhub.cloud.shop.redis.MyRedisTemplate;
import com.pronhub.cloud.shop.redis.SeckillKeyPrefix;
import com.pronhub.cloud.shop.service.ISeckillGoodService;
import com.pronhub.cloud.shop.web.vo.SeckillGoodVo;
import com.pronhub.shop.cloud.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/seckillGood")
public class SeckillCOntroller {
    //Redis数据库的预热用到的
    @Autowired
    private MyRedisTemplate myRedisTemplate;

    @Autowired
    private ISeckillGoodService seckillGoodService;

    //Redis
    //秒杀商品的页面详情
    @RequestMapping("/query")//264次每秒  Redis779次PSC
    public Result<List<SeckillGoodVo>> query(){
        return Result.success(seckillGoodService.queryFormCache());
    }
    @RequestMapping("/find")
    public Result<SeckillGoodVo> find(Long seckillId){
        SeckillGoodVo vo = seckillGoodService.findByIdFromCache(seckillId);
        vo.setStockCount(myRedisTemplate.get(SeckillKeyPrefix.SECKILL_STOCK_COUNT,seckillId+"",Integer.class));
        return Result.success(vo);
    }

    /**
     * 这些功能本来应该在后台实现的 但是并不是我们这个业务方法 我们这上单出在这里初始化
     * @return
     */
    @RequestMapping("/initData")
    public Result<String> initData(){
        //1.把所有的秒杀商品库存存储到redis
        List<SeckillGoodVo> seckillGoodVoList = seckillGoodService.query();
        for(SeckillGoodVo vo:seckillGoodVoList){
            myRedisTemplate.set(SeckillKeyPrefix.SECKILL_STOCK_COUNT,vo.getId()+"",vo.getStockCount());
            //2.初始化Redis里面的数值
            myRedisTemplate.hset(SeckillKeyPrefix.SECKILL_GOOD_HASH,"",vo.getId()+"",vo);
        }
        return Result.success("初始化成功");
    }
}
